#include "BieuThucIO.h"

list<double> BieuThucIO::chuyenDuLieuVaoMang(char* tenTapTin){
	list<double> arr;
	ifstream inputFile(tenTapTin);
	if(!inputFile){
		cout<<"Khong mo duoc file"; return arr;
	}
	
	double so;
	while(!inputFile.eof()){
		inputFile >> so;
		arr.push_back(so);
	}
	inputFile.close();
	return arr;
}

BieuThuc* BieuThucIO::chuyenMangThanhBieuThuc(list<double> &arr){
	BieuThuc* bt;

	if(arr.size()>0){
		if(arr.front() == 0){
			arr.pop_front();
			bt = new BieuThucHang(arr.front());
			arr.pop_front();
		}
		else{
			if(arr.front() == 1){
				arr.pop_front();
				double arr0 = arr.front();
				arr.pop_front();
				double arr1 = arr.front();
				arr.pop_front();
				bt = new BieuThucDon(arr0, arr1);
			}
			else{
				if(arr.front() == 2){
					arr.pop_front();
					BieuThuc* bieuThuc1 = chuyenMangThanhBieuThuc(arr);
					BieuThuc* bieuThuc2 = chuyenMangThanhBieuThuc(arr);
					bt = new BieuThucTong(bieuThuc1, bieuThuc2);
				}
				else{
					if(arr.front() == 3){
						arr.pop_front();
						BieuThuc* bieuThuc1 = chuyenMangThanhBieuThuc(arr);
						BieuThuc* bieuThuc2 = chuyenMangThanhBieuThuc(arr);
						bt = new BieuThucTich(bieuThuc1, bieuThuc2);
					}
					else{
						if(arr.front() == 4){
							arr.pop_front();
							BieuThuc* bieuThuc1 = chuyenMangThanhBieuThuc(arr);
							BieuThuc* bieuThuc2 = chuyenMangThanhBieuThuc(arr);
							bt = new BieuThucChia(bieuThuc1, bieuThuc2);
						}
					}
				}
			}
		}
	}
	return bt;
}

void BieuThucIO::luuGiaTriX(list<double> &arr){
	this->giaTriX = arr.back();
	arr.pop_back();
}

BieuThuc* BieuThucIO::input(char* tenTapTinInput){
	list<double> arr = chuyenDuLieuVaoMang(tenTapTinInput);
	luuGiaTriX(arr);
	BieuThuc* bieuThuc = chuyenMangThanhBieuThuc(arr);
	return bieuThuc;
}


bool BieuThucIO::output(char* tenTapTinOutput, double ketQuaGiaTri, BieuThuc* ketQuaDaoHam){
	string ketQuaDH = ketQuaDaoHam->xuatChuoi();
	ketQuaDH = xuLyChuoiKetQuaDaoHam(ketQuaDH);
	std::ostringstream sstr;
	sstr << ketQuaGiaTri;
	string s = sstr.str();
	string ketQuaOutput = s + '\n' + ketQuaDH;
	//output ra file
	ofstream outFile(tenTapTinOutput, ios::app);
	if(!outFile){
		cout << "Khong mo duoc tap tin" << endl;
		return false;
	}
	
	int num = ketQuaOutput.size();
	for(int i=0; i<num; i++){
		outFile.put(ketQuaOutput[i]);
	}
	outFile.close();
	return true;
}

double BieuThucIO::layGiaTriX(){
	return this->giaTriX;
}

string BieuThucIO::xuLyChuoiKetQuaDaoHam(string chuoi){
	string kq = "";
	
	int num = chuoi.size();
	for(int i=0; i<num; i++){
		if(chuoi[i] == '+' && chuoi[i+1] == '-'){
			for(int j = i; j < num-1; j++){
				chuoi[j] = chuoi[j+1];			
			}
			chuoi.pop_back();
			num--;
		}
	}
	kq = chuoi;

	return kq;
}